from fontTools.ttLib import TTFont
import ddddocr
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont


def convert_cmap_to_image(cmap_code, font_path):
    '''
    将 cmap code 转换为图像对象
    :param cmap_code:Unicode码点
    :param font_path:字体文件路径
    :return:
    '''
    img_size = 1024
    # 准备三要素：image画布  draw画笔 font字体
    img = Image.new("1", (img_size, img_size), 255)  # 创建一个黑白图像对象
    draw = ImageDraw.Draw(img)  # 创建绘图对象
    font = ImageFont.truetype(font_path, int(img_size * 0.6))  # 加载字体文件

    # 将 cmap code 转换为字符
    character = chr(cmap_code)
    # print("character:",character)
    bbox = draw.textbbox((0, 0), character, font=font)  # 获取文本在图像中的边界框
    width = bbox[2] - bbox[0]  # 文本的宽度
    height = bbox[3] - bbox[1]  # 文本的高度
    draw.text(((img_size - width) // 2, (img_size - height) // 6), character, font=font)  # 绘制文本，并居中显示
    return img


def extract_text_from_font(font_path):
    '''
    提取字体文件中的所有字符
    :param font_path:
    :return:
    '''
    font = TTFont(font_path)  # 加载字体文件
    # font.saveXML("xxx.xml")
    # 图像识别的模块：DdddOcr
    ocr = ddddocr.DdddOcr(beta=True, show_ad=False)  # 实例化 ddddocr 对象

    # print("font.getBestCmap().items():", font.getBestCmap().items())

    font_map = {}
    for cmap_code, glyph_name in font.getBestCmap().items():
        image = convert_cmap_to_image(cmap_code, font_path)  # 将字体字符转换为图像

        # 提取图像字符
        bytes_io = BytesIO()
        image.save(bytes_io, "PNG")
        text = ocr.classification(bytes_io.getvalue())  # 图像识别
        # print("text:", text)
        image.save(f"./imgs/{text}.png", "PNG")  # 保存图像
        # print(f"Unicode码点：{cmap_code} - Unicode字符:{glyph_name}，识别结果：{text}")
        font_map[hex(cmap_code).replace("0x", r"")] = text   # 猫眼电影特例将 Unicode 码点转换为 HTML 实体
    print(font_map)

    return font_map


# font_file_path = "96fc7b50b772f52-700.woff2"
# print(extract_text_from_font(font_file_path))
